package fu.k4c.vTeam.Login;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;

import fu.k4c.vTeam.R;
import fu.k4c.vTeam.Object.ChangePass;

public class ChangePasswordActivity extends Activity {
	ProgressDialog proDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.change_pass_activity);
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
				.permitAll().build();
		StrictMode.setThreadPolicy(policy);
		Bundle data = getIntent().getExtras();
		final String email = data.getString("email");
		overridePendingTransition(android.R.anim.fade_in,
				android.R.anim.fade_out);
		Button btn_submit = (Button) findViewById(R.id.btn_change_pass_submit);
		Button btn_cancel = (Button) findViewById(R.id.btn_change_pass_cancel);
		Button btn_back = (Button) findViewById(R.id.btn_change_pass_back);
		btn_cancel.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		btn_back.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		btn_submit.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				new AsyncTask<Void, Void, Void>() {
					ChangePass acc;
					String old_pass,new_pass,re_new_pass;
					boolean tmp =false;

					@Override
					protected Void doInBackground(Void... params) {
						// TODO Auto-generated method stub
										try {
											SchemeRegistry registry = new SchemeRegistry();
											registry.register(new Scheme(
													"http",
													PlainSocketFactory
															.getSocketFactory(),
													80));
											HttpParams httpParams = new BasicHttpParams();
											ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(
													httpParams, registry);
											HttpClient client = new DefaultHttpClient(
													connMgr, httpParams);
											HttpPost post = new HttpPost(
													getString(R.string.connectionString)
															+ "vLocationService/changepassword");
											post.setHeader("Accept",
													"application/json");
											post.setHeader("Content-type",
													"application/json");
											HashMap<String, Object> postParameters = new HashMap<String, Object>();
											postParameters.put("UserName",
													email);
											postParameters.put("OldPass",
													encryptPassword(old_pass));
											postParameters.put("NewPass",
													encryptPassword(new_pass));
											Gson gson = new Gson();
											String jsonParameters = gson
													.toJson(postParameters);
											post.setEntity(new StringEntity(
													jsonParameters));
											HttpResponse response = client
													.execute(post);
											HttpEntity entity = response
													.getEntity();
											String jsonresult = EntityUtils
													.toString(entity);
											acc = gson.fromJson(jsonresult,
													ChangePass.class);
										} catch (Exception e) {
											// TODO: handle exception

											tmp = true;
										}
						return null;
					}

					protected void onPostExecute(Void result) {
						proDialog.dismiss();
						if(tmp)
						{
							Toast.makeText(
									getApplicationContext(),
									"Bạn vui lòng kiểm tra lại kết nối Internet",
									Toast.LENGTH_LONG).show();
						}
						else
						if (acc.getStatuschangepassword().equals("False")) {
							Toast.makeText(getApplicationContext(),
									"Bạn đã nhập sai mật khẩu",
									Toast.LENGTH_LONG).show();
						} else {
							proDialog.dismiss();
							Toast.makeText(getApplicationContext(),
									"Thay đổi mật khẩu thành công",
									Toast.LENGTH_LONG).show();
							finish();
						}
					};

					protected void onPreExecute() {
						EditText oldpass = (EditText) findViewById(R.id.et_change_pass_old);
						old_pass = oldpass.getText()
								.toString();
						EditText newpass = (EditText) findViewById(R.id.et_change_pass_new1);
						new_pass = newpass.getText()
								.toString();
						EditText renewpass = (EditText) findViewById(R.id.et_change_pass_new2);
						re_new_pass = renewpass.getText()
								.toString();
						if (old_pass.trim() == null
								|| new_pass.trim() == null
								|| re_new_pass.trim() == null) {
							Toast.makeText(
									getApplicationContext(),
									"Vui lòng nhập đầy đủ mật khẩu",
									Toast.LENGTH_LONG).show();
						} else if (!new_pass.equals(re_new_pass)) {
							Toast.makeText(
									getApplicationContext(),
									"Mật khẩu mới không khớp nhau, vui lòng nhập lại",
									Toast.LENGTH_LONG).show();
						} else if (new_pass.length() < 6) {
							Toast.makeText(getApplicationContext(),
									"Mật khẩu có ít nhất 6 ký tự",
									Toast.LENGTH_LONG).show();
						} else if (new_pass.equals(old_pass)) {
							Toast.makeText(
									getApplicationContext(),
									"Mật khẩu cũ và mật khẩu mới trùng nhau",
									Toast.LENGTH_LONG).show();
						} else {
							proDialog = new ProgressDialog(
									ChangePasswordActivity.this);
							proDialog.setMessage("Đang kết nối đến máy chủ...");
							proDialog.setCancelable(false);
							proDialog.show();
						}
					};

					protected void onProgressUpdate(Void... values) {
					}

				}.execute();

			}
		});
	}

	private static String encryptPassword(String password) {
		String sha1 = "";
		try {
			MessageDigest crypt = MessageDigest.getInstance("SHA-1");
			crypt.reset();
			crypt.update(password.getBytes("UTF-8"));
			sha1 = byteToHex(crypt.digest());
			sha1 = sha1.toUpperCase();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return sha1;
	}

	private static String byteToHex(final byte[] hash) {
		Formatter formatter = new Formatter();
		for (byte b : hash) {
			formatter.format("%02x", b);
		}
		return formatter.toString();
	}

}
